package com.guigu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guigu.mapper.CartMapper;
import com.guigu.pojo.Cart;
import com.guigu.pojo.Product;
import com.guigu.service.CartService;
import com.guigu.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 购物车表 服务实现类
 * </p>
 *
 * @author Mr.Zhang
 * @since 2025-03-12
 */
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {

    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private ProductService productService;

    @Override
    public List<Cart> getCartByConsumerId(Integer consumerId) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("consumer_id",consumerId);
        List<Cart> carts = cartMapper.selectList(queryWrapper);
        for (Cart cart : carts) {
            Product product = productService.getById(cart.getProductId());
            cart.setProduct(product);
        }
        return carts;
    }

    @Override
    public boolean addToCart(Cart cart) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("consumer_id",cart.getConsumerId());
        queryWrapper.eq("product_id",cart.getProductId());
        if (cartMapper.selectList(queryWrapper).isEmpty()){
            cartMapper.insert(cart);
            return true;
        }else if (cartMapper.selectList(queryWrapper).size() == 1){
            Cart cart1 = cartMapper.selectList(queryWrapper).get(0);
            cart1.setNum(cart1.getNum()+cart.getNum());
            cartMapper.updateById(cart1);
            return true;
        }
        return false;
    }
}
